package course.cmsc436.medicationmanager;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.AsyncTask;
import android.util.Log;

/*
 * Class for creating, executing, and parsing a UPC lookup.
 */
public class UPCFetcher {
	private static final String UPC_FAIL = "The UPC that was given was incorrect or invalid.";
	private static String TAG = UPCFetcher.class.getSimpleName();
	private static Pattern DESC = Pattern.compile("<td>Description</td><td></td><td>([^<]*)</td>");
	
	private String upc;
	private String response;
	private String result;
	/*
	 * The UPC code should be a number with either 8 or 12 digits, in string format.
	 */
	public UPCFetcher(String code) {
		this.upc = code;
		this.response = null;
		this.result = null;
	}
	
	private void doRequest() throws MalformedURLException {
		try {
			URL url = new URL("http://www.upcdatabase.com/item/" + this.upc);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			BufferedReader br = new BufferedReader(
				new InputStreamReader(
						new BufferedInputStream(conn.getInputStream())));
			String result = "";
			String line; 
			while((line = br.readLine()) != null) {
				result += line + "\n";
			}
			this.response = result;
		} catch (Exception e) {
			Log.e(TAG, "Could not do request", e);
		}
	}

	private void parseRequest() {
		Log.d(TAG, this.response);
		try {
			Matcher m = DESC.matcher(response);
			m.find();
			String desc = m.group(1);
			result = desc;
		} catch (Exception e) {
			Log.i(TAG, "Matcher broke", e);
			result = "Not found";
		}
	}
	
	public String getProductName() {
		try {
			doRequest();
			parseRequest();
		} catch (MalformedURLException e) {
			Log.e(TAG, "Invalid URL given", e);
		}
		return result;
	}
	
	public static AsyncTask<String, Void, String> doAsync(String s, final FetchCompleteListener fcl) {
		Log.d(TAG, s);
		return new AsyncTask<String, Void, String>(){

			@Override
			protected String doInBackground(String... params) {
				try {
					UPCFetcher f = new UPCFetcher(params[0]);
					return f.getProductName();
				} catch (Exception e) {
					return "ERROR";
				}
			}
			
			@Override
			protected void onPostExecute(String result) {
				fcl.onFetchComplete(result);
			}
		}.execute(s);
	}
	
	public interface FetchCompleteListener {
		void onFetchComplete(String desc);
	};

}
